<template>
  <view class="w-full">
    <text class="text-lg font-bold p-4 block">居家医护</text>

    <view class="px-2 box-border flex flex-nowrap overflow-x-auto gap-[10rpx] mb-2">
      <view
        v-for="(item, i) in professionList"
        :key="i"
        :class="selectedNurseIndex === i ? 'active' : ''"
        class="notm"
        @click="selectedNurseIndex = i"
      >
        {{ item }}
      </view>
    </view>
    
    <ThreeLevelDirectory 
      ref="directoryRef"
      :show-add-button="true"
      :add-button-text="addButtonText"
      @change="onDirectoryChange"
      @add="onAddItem">
      
      <!-- 内容插槽 -->
      <template #content="{ currentItem, level1, level2 }">
        <view v-if="loading" class="text-center text-gray-500 py-8">
          <text>加载中...</text>
        </view>
        
        <view v-else-if="currentItem && nurseList.length > 0" class="two-column-layout">
          <view class="item-card" v-for="item in nurseList" :key="item.id" @click="onNurseClick(item)">
            <image :src="getAvatar(item.avatar) || defaultAvatar" mode="aspectFill" class="item-image"></image>
            <view class="mt-2">
              <text class="text-[24rpx] text-[#999] truncate">{{ item.name || '未知' }}</text>
            </view>
          </view>
        </view>
        
        <view v-else class="text-center text-gray-500 py-8">
          <text>{{ currentItem ? '暂无数据' : '请选择三级目录项查看内容' }}</text>
        </view>
      </template>
    </ThreeLevelDirectory>

    <!-- 添加标签弹窗 -->
    <nut-popup 
      v-model:visible="showAddPopup" 
      position="center" 
      :style="{ width: '80%', borderRadius: '24rpx' }"
    >
      <view class="add-popup">
        <view class="popup-header">
          <text class="popup-title">添加{{ addLevelText }}</text>
        </view>
        
        <view class="popup-content">
          <nut-input
            v-model="addTagName"
            :placeholder="`请输入${addLevelText}名称`"
            :maxlength="50"
            clearable
            class="tag-input"
          />
        </view>
        
        <view class="popup-footer">
          <nut-button 
            type="default" 
            class="flex-1"
            @click="closeAddPopup"
          >
            取消
          </nut-button>
          <nut-button 
            type="primary" 
            class="flex-1 ml-3"
            @click="confirmAddTag"
          >
            确定
          </nut-button>
        </view>
      </view>
    </nut-popup>
  </view>
</template>

<script setup>
import { ref, watch } from "vue";
import ThreeLevelDirectory from "./ThreeLevelDirectory.vue";
import { request } from "@/service/request";
import Taro from "@tarojs/taro";
import defaultAvatar from "./assets/bao.png";
import { useImage } from '@/hooks'

const getAvatar = (avatar) => {
  if (avatar) {
    return useImage(avatar);
  }
  return defaultAvatar;
};

// 添加按钮文本配置
const addButtonText = ref({
  level1: "添加部门",
  level2: "添加科室",
  level3: "添加项目"
});

// 职业类型列表
const professionList = ref([
  '医生',
  '护士',
  '康复师',
  '技师',
  '药剂师',
  '营养师',
  '心理咨询师',
  '社工师',
  '医疗护理员',
  '养老护理员',
  '母婴护理员',
  '新家政服务员',
  '老家政服务员'
]);

// 护士列表数据
const nurseList = ref([]);
const loading = ref(false);
const currentSelectedItem = ref(null);

// 选中的职业索引
const selectedNurseIndex = ref(1);

// 三级目录组件ref
const directoryRef = ref(null);

// 添加标签弹窗相关
const showAddPopup = ref(false);
const addTagName = ref('');
const addLevelText = ref('');
const addParentId = ref(null);

// 获取护士列表
const getNurseList = async (tagId) => {
  try {
    loading.value = true;
    console.log("获取护士列表, tagId:", tagId);
    
    const params = {
      pageSize: 12,
      pageNo: 1,
      isHealth: 1
    };
    
    // 如果有tagId，添加到参数中
    if (tagId) {
      params.tagId = tagId;
    }
    
    const res = await request.get('/nurse_nurses/nurseNurses/list', params, {
      useErrMsg: true
    });
    
    console.log("护士列表数据:", res);
    
    if (res.success && res.success.records) {
      nurseList.value = res.success.records;
    } else if (res.success && Array.isArray(res.success)) {
      nurseList.value = res.success;
    } else {
      nurseList.value = [];
    }
  } catch (error) {
    console.error("获取护士列表失败:", error);
    nurseList.value = [];
  } finally {
    loading.value = false;
  }
};

// 目录变化事件
const onDirectoryChange = ({ level, item }) => {
  console.log(`目录变化 - 级别${level}:`, item);
  currentSelectedItem.value = item;
  
  // 第三级目录变化时，获取护士列表
  if (level === 3 && item && !item.isAddButton) {
    getNurseList(item.id);
  }
};

// 添加项目事件
const onAddItem = ({ level, parentId }) => {
  console.log(`添加项目 - 级别${level}, 父级ID:`, parentId);
  
  const levelText = level === 1 ? '部门' : level === 2 ? '科室' : '项目';
  
  // 设置弹窗数据
  addLevelText.value = levelText;
  addParentId.value = parentId;
  addTagName.value = '';
  
  // 显示弹窗
  showAddPopup.value = true;
};

// 关闭添加弹窗
const closeAddPopup = () => {
  showAddPopup.value = false;
  addTagName.value = '';
};

// 确认添加
const confirmAddTag = async () => {
  const name = addTagName.value.trim();
  
  if (!name) {
    Taro.showToast({
      title: '名称不能为空',
      icon: 'none'
    });
    return;
  }
  
  // 关闭弹窗
  showAddPopup.value = false;
  
  // 调用接口添加
  await addTag(name, addParentId.value, addLevelText.value);
};

// 添加标签
const addTag = async (name, pid, levelText) => {
  try {
    Taro.showLoading({
      title: '添加中...'
    });
    
    const params = {
      name,
      projectid: pid || null
    };
    
    console.log('添加标签参数:', params);
    
    const res = await request.post('/health_records/health_tag_info/healthTagInfo/add', params, {
      useErrMsg: true
    });
    
    console.log('添加标签结果:', res);
    
    if (res.success) {
      Taro.hideLoading();
      Taro.showToast({
        title: `${levelText}添加成功`,
        icon: 'success'
      });
      
      // 刷新三级目录数据
      setTimeout(() => {
        if (directoryRef.value && directoryRef.value.refresh) {
          directoryRef.value.refresh();
        }
      }, 1500);
    } else {
      Taro.hideLoading();
      Taro.showToast({
        title: res.message || '添加失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('添加标签失败:', error);
    Taro.hideLoading();
    Taro.showToast({
      title: '添加失败',
      icon: 'none'
    });
  }
};

// 护士点击事件
const onNurseClick = (nurse) => {
  Taro.navigateTo({
    url: `/pages/copy/nuser-detail?id=${nurse.id}`
  });
};
</script>

<style lang="scss">
.notm{
  white-space: nowrap;
  padding: 10rpx 20rpx;
  border-bottom: 2rpx solid #f0f0f0;
  color: #999;
  &.active{
    color: #0667f8;
    border-bottom: 2rpx solid #0667f8;
  }
}
.two-column-layout {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  
  .item-card {
    flex: 0 0 calc(30% - 8rpx);
    padding: 32rpx 10rpx;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    
    .item-image {
      width: 112rpx;
      height: 112rpx;
      background-color: #909090;
      border-radius: 50%;
      display: block;
      flex-shrink: 0;
    }
  }
}

.add-popup {
  padding: 32rpx;
  
  .popup-header {
    text-align: center;
    padding-bottom: 24rpx;
    border-bottom: 1rpx solid #f0f0f0;
    margin-bottom: 32rpx;
    
    .popup-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .popup-content {
    padding: 16rpx 0;
    
    .tag-input {
      :deep(.nut-input) {
        border: 1rpx solid #e0e0e0;
        border-radius: 12rpx;
        padding: 16rpx 24rpx;
        font-size: 28rpx;
      }
    }
  }
  
  .popup-footer {
    display: flex;
    gap: 24rpx;
    margin-top: 32rpx;
    
    .nut-button {
      flex: 1;
      height: 80rpx;
      border-radius: 12rpx;
      font-size: 28rpx;
    }
  }
}
</style>
